<template>
  <div>
    <a-button
        class="mb12"
        type="primary"
        @click="add('add')"
        >新增{{btnName}}</a-button
    >
    <a-table :columns="columns" rowKey="id" :data-source="committeeList" bordered size="small" :pagination="false" :scroll="{ y: 195 }">
      <template slot="userId" slot-scope="text, record, index">
        <SelectMember :value="{ key: record.userId || '', label: record.userName || '' }"
          placeholder="请选择委员"
          labelInValue
          @isChange="(val, opt) => { handleChange(selectedMember(val, opt), record.id, ['userId', 'userName', 'phone', 'employeeNum'])}"
        >
          <!-- :dataList="memberData" -->
          <!-- @change="(val, opt) => { handleChange(selectedMember(val), record.id, ['userId', 'userName', 'phone', 'employeeNum']) }" -->
        </SelectMember>
      </template>
      <template slot="youthPost" slot-scope="text, record, index">
        <a-select
          style="width: 100%;"
          v-model='text' 
          :show-search="true" 
          :not-found-content="null" 
          :show-arrow="false" 
          :filter-option="true"
          :autoClearSearchValue="false"
          @search="(val) => { handleChange(val, record.id, 'youthPost')}"
          @blur="(val) => { handleBlur(val, record.id, 'youthPost') }"
          @change="(val, opt) => { handleChange(val, record.id, 'youthPost') }">
        	<a-select-option v-for="(item, index) in youthPostList" :key="item"> {{item}}</a-select-option>
        </a-select>
      </template>
      <template slot="action" slot-scope="text, record">
        <a @click="deleteRow(record.id)">删除</a>
      </template>
    </a-table>
  </div>
</template>

<script>
import { STable } from '@/components' // 表格
import SelectMember from '../../componments/employeeSelect.vue'
import { queryAllYouthMemberList } from '@/api/partyMasses/leagueManage'
export default {
  name:'a'+ Date.now(),
  // name: 'AddPerson',
  components: {
    SelectMember,
    STable,
  },
  props: {
    orgType: {
      type: [Number, String],
      default() {
        return 1
      }
    },
    committeeList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  computed: {
    btnName() {
      const map = {
        '1': '团委委员',
        '2': '总支委员',
        '3': '支部委员'
      }
      return map[this.orgType]
    },
    youthPostSelectData() {
      return this.youthPostList;
    }, 
    columns() {
      return [
          {
              title: '序号',
              width: 60,
              dataIndex: 'index',
              customRender() {
                  return arguments[2] + 1
              },
          },
          {
              title: this.btnName,
              dataIndex: 'userId',
              width: 200,
              scopedSlots: { customRender: 'userId' },
          },
          {
              title: '团内职务',
              width: 200,
              dataIndex: 'youthPost',
              scopedSlots: { customRender: 'youthPost' },
          },
          {
              title: '员工编号',
              ellipsis: true,
              dataIndex: 'employeeNum',
          },
          {
              title: '电话号码',
              dataIndex: 'phone',
              ellipsis: true,
          },
          {
              title: '操作',
              dataIndex: 'action',
              width: '80px',
              align: 'center',
              scopedSlots: { customRender: 'action' },
          }
        ]
    },
  },
  data() {
      return {
        loadData: (parameter) => {
            const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
            return this.getTableList(requestParameters).then((res) => {
              return res
            });
        }, // 加载数据方法 必须为 Promise 对象
        detail: {
          form: {
            name: '111',
            parentName: '000',
            orgType: '党委',
            orgStatus: '正常',
            creatTime: '2020-05-12',
            orgSecretaryName: '李书记',
            subSecretaryName: '李副书记',
            management: '张管理员',
            changeTime: '2020-05-13'
          }
        },
        tableData: [],
        memberData: [],
        youthPostList: [ '委员', '宣传委员', '组织委员' ]// 委员、宣传委员、组织委员
      }
  },
  mounted() {
    // getPartyOrganizationById({id: this.$route.query.id}).then((res) => {
    //   console.log(res)
    // })
    // queryAllYouthMemberList({}).then((res) => {
    //   if (res && res.code == 0) {
    //     this.memberData = res.data;
    //   }
    // })
    // this.getTableList().then((res) => {
    //   this.committeeList = res.data;
    // })
  },
  methods: {
    createRandomId() {
      return (Math.random()*10000000).toString(16).substr(0,4)+''+(new Date()).getTime()+''+Math.random().toString().substr(2,5);
    },
    add() {
      let id = this.createRandomId();
      const newData = [...this.committeeList];
      newData.push({
        id: id,
        userId: null,
        userName: null,
        youthPost: null,
        employeeNum: null,
        phone: null
      })
      this.$emit('update:committeeList', newData)
    },
    selectedMember(val, opt) {
      if (!val) return {};
      const has = this.committeeList.some((item, index) => {
        return val == item.userId
      })
      if (has) {
        this.$message.error('所选委员已存在！');
        return {};
      }
      const obj = {
        userId: opt.userId,
        userName: opt.name,
        phone: opt.phone,
        employeeNum: opt.jobNum
      }
      return obj;
      // return this.memberData.filter(e => e.userId == val)[0]
    },
    handleBlur(value, key, dataIndex){
      if(this.youthPostList.indexOf(value)==-1){
        this.youthPostList.push(value);
      }
      this.handleChange(value, key, dataIndex)
    },
    handleChange(value, key, dataIndex, type) {
      const newData = [...this.committeeList];
      const target = newData.filter(item => key === item.id)[0];
      if (target) {
        if (typeof(value) == 'object') {
          dataIndex.forEach((item) => {
            target[item] = value[item]
          })
        } else {
          target[dataIndex] = value;
        }
        this.$emit('update:committeeList', newData)
      }
    },
    deleteRow(key) {
      const data = [...this.committeeList];
      const newData = data.filter(item => key !== item.id);
      this.$emit('update:committeeList', newData)
    },
    getTableList() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve({
            code: 200,
            currentPage: 1,
            data: [
              { id: 1, userName: undefined, youthPost: '', prepareTime: '2020-05-12', employeeNum: 1000, becomeTime: '2020-06-02', phone: '18982333333', currentPost: '西南公司/工程管理部/业务主办'},
            ],
            pageSize: 10,
            success: true,
            totalPage: 1,
            totalSize: 0,
          })
        }, 1000)
      })
    },
    handleClose() {
      this.$multiTab.close(this.$route.fullpath);
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    }
  }
}
</script>

<style lang="less" scoped>
  .ant-form-item{
    display: flex;
  }
  .btn_box .ant-affix{
    overflow: hidden;
    button {
      float: right;
    }
  }
</style>
